External Exam Download Resources Web Applications Games Recycle Bin

Flask file uploads

Make sure you create empty static folder for file to upload to.

templates\template.html

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File">
</form>

server.py

from flask import *
app = Flask("uploading files to webserver")
import os, sys

@app.route("/upload", methods=["POST"])
def upload():
    file = request.files["fileToUpload"]
    #to avoid a 'permission error (13)', we find absolute location of this module:
    disk_location = os.path.dirname(os.path.realpath(sys.argv[0]))
    save_location = os.path.join(disk_location, "static")
    file.save(os.path.join(save_location, file.filename))
    return redirect("/")
  
@app.route("/")
def main():
    return render_template("template.html")
 
app.run(debug=True)

The following extensions to this program displays the files uploaded:

1. add browse utility function and modify main route as shown:

# utility function: browse, returns list of files in static folder:
def browse():
    filelist = []
    static_folder = os.path.join(app.root_path,"static")
    for entry in os.scandir(static_folder):
        if not entry.name.startswith('.') and not entry.is_dir():
            filelist.append(entry.name)
    return filelist
  
@app.route("/")
def main():
    files = browse()
    return render_template("template.html", files=files)

2. add Jinja2 code to template.html to iterate through and display files:

{% if files|length > 1 %}
  {% for file in files %}
    <a href="{{ url_for('static', filename=file) }}">{{file}}</a>
  {% endfor %}
{% endif %}